import React, { Component, createRef } from 'react'

export default class Form extends Component {

  constructor() {
    super();
    this.state = {
      name: '',
      sex: "1",
      desc: '',
      city: ["2", "3"],
      hobby:["001"]
    }
    this.address = createRef()
  }

  handleSubmit = () => {
    console.log('submit', this.address.current.value)

  }

  handleChange(event) {
    let val = event.target.value;
    let name = event.target.name;

    if(name==='hobby'){
      val = event.target.value;
      let index = this.state.hobby.indexOf(val);
      if (index > -1) {
        this.state.hobby.splice(index, 1)
      } else {
        this.state.hobby.push(val)
      }
      this.setState({})
      return;
    }

    if (name === 'city') {
      val = event.target.selectedOptions[0].value;
      let index = this.state.city.indexOf(val);
      if (index > -1) {
        this.state.city.splice(index, 1)
      } else {
        this.state.city.push(val)
      }
      this.setState({})
      return;
    }
    this.setState({
      [name]: val.toUpperCase()
    })
  }

  render() {
    return (
      <div>
        名称: <input type="text" name="name" value={this.state.name}
          onChange={this.handleChange.bind(this)}
        /> <br></br>
        性别：
        <input type="radio" name="sex" value="1"
          checked={this.state.sex === '1' ? true : false}
          onChange={this.handleChange.bind(this)}
        />男
        <input type="radio" name="sex" value="2"
          checked={this.state.sex === '2' ? true : false}
          onChange={this.handleChange.bind(this)}
        />女
        <br></br>
描述：<textarea name="desc" cols="30" rows="10"

          onChange={this.handleChange.bind(this)}
        ></textarea>
        <br></br>
        城市：<select name="city"
          multiple
          onChange={this.handleChange.bind(this)}
          value={this.state.city}
        >
          <option value="1">北京</option>
          <option value="2">上海</option>
          <option value="3">天津</option>

        </select>

        {/* <input type="text" name="address" ref="address" id=""/> */}
        <input type="text" name="address" ref={this.address} id="" />
        <br></br>

爱好：

        <input type="checkbox" 
        checked={this.state.hobby.indexOf('001')>-1} 
        onChange={this.handleChange.bind(this)}
        name="hobby" value="001" /> 吃饭
        <input type="checkbox" name="hobby" value="002"
        checked={this.state.hobby.indexOf('002')>-1}
        onChange={this.handleChange.bind(this)}
        /> 睡觉
        <input type="checkbox" name="hobby" value="003"
        checked={this.state.hobby.indexOf('003')>-1}
        onChange={this.handleChange.bind(this)}
        /> 打豆豆
        <button onClick={this.handleSubmit}>提交</button>

        <hr />

        城市：{this.state.city}

      </div>
    )
  }
}
